package com.mengniu.commerce.collect.service.impl.order;


import com.mengniu.commerce.collect.common.enums.MnBannerEnum;
import com.mengniu.commerce.collect.common.enums.WmAmountTypeEnum;
import com.mengniu.commerce.collect.service.WmOrderService;
import com.mengniu.commerce.collect.third.request.IWeiMengOrderRequest;
import com.mengniu.commerce.collect.third.response.order.BaseOrderInfoResponse;
import com.mengniu.commerce.collect.third.response.order.OrderInfoResponse;
import com.mengniu.commerce.collect.third.response.order.OrderListResponse;
import com.mengniu.commerce.collect.util.RestTemplateUtil;
import com.mengniu.commerce.common.core.enums.SourceEnum;
import com.mengniu.commerce.common.core.utils.DateUtils;
import com.mengniu.commerce.sync.api.RemoteOrderService;
import com.mengniu.commerce.sync.api.domain.CreateOrderModel;
import com.mengniu.commerce.sync.api.domain.ModifyOrderModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;


/**
 * 订单管理 服务层实现
 *
 * @author yz_sm
 */
@Service
public class WmOrderServiceImpl implements WmOrderService
{

    @Autowired
    private RestTemplateUtil restTemplateUtil;

    @Resource
    private RemoteOrderService remoteOrderService;

    @Autowired
    private IWeiMengOrderRequest weiMengOrderRequest;


    /***
    * @Description: 创建订单
    * @Param: [bosId, orderNo]
    * @return: void
    * @Author: zfw
    * @Date: 2023/12/4
    * @Date: 19:23
    */
    @Override
    public void createOrderByMessage(Long bosId,Long orderNo) {
        List<CreateOrderModel> list = new ArrayList<>();
        //查询订单
        String token = restTemplateUtil.getToken(bosId);
        //通过id查询订单详情进行参数封装
        OrderInfoResponse orderInfoResponse = weiMengOrderRequest.getOrderInfoById(orderNo, token);
        CreateOrderModel createOrderModel = new  CreateOrderModel();
        list.add(this.convert(orderInfoResponse.getData() ,createOrderModel));
        remoteOrderService.createOrder(list, SourceEnum.WM.getSource());
    }

    /***
    * @Description: 通过微盟消息修改订单
    * @Param: []
    * @return: void
    * @Author: zfw
    * @Date: 2023/12/3
    * @Date: 12:07
    */
    @Override
    public void updateOrderByMessage(Long bosId,Long goodsId) {
        ModifyOrderModel modifyOrderModel = new ModifyOrderModel();
        //查询订单
        String token = restTemplateUtil.getToken(bosId);
        //通过id查询订单详情进行参数封装
        OrderInfoResponse orderInfoResponse = weiMengOrderRequest.getOrderInfoById(goodsId, token);
        modifyOrderModel = this.convertUpdate(orderInfoResponse,modifyOrderModel);
        remoteOrderService.modify(modifyOrderModel, SourceEnum.WM.getSource());
    }

    /***
    * @Description: 存量订单数据创建到蒙牛
    * @Param: []
    * @return: void
    * @Author: zfw
    * @Date: 2023/12/3
    * @Date: 14:20
    */
    @Override
    public void createStockOrderToMengNiu(Long  bosId) {
        List<CreateOrderModel> list = new ArrayList<>();
        //查询订单
        String token = restTemplateUtil.getToken(bosId);
        //首先获取订单列表总数
        OrderListResponse orderInfoResponse = weiMengOrderRequest.getOrderList(1,1,token);
        //订单总数
        int totalCount = orderInfoResponse.getPageList().getTotalCount();
        int pageSize = 20;
        int pageNum ;
        int pageTotal = (int) Math.ceil(totalCount * 1.0 / pageSize);
        for(int i=1;i<=pageTotal;i++){
            pageNum = i ;
            //调用蒙牛接口查询订单
            OrderListResponse orderList = weiMengOrderRequest.getOrderList(pageNum, pageSize,token);
            //循环订单
            List<OrderInfoResponse.Data> pageList = orderList.getPageList().getPageList();
            for (OrderInfoResponse.Data pl:pageList){
                CreateOrderModel createOrderModel = new CreateOrderModel();
                //通过id查询订单详情进行参数封装
                list.add(this.convert(pl,createOrderModel));
            }
        }
        remoteOrderService.createOrder(list, SourceEnum.WM.getSource());
    }

    /***
     * 修改订单
     * @param
     * @param orderInfoResponse
     * @param order
     * @return
     */
    public ModifyOrderModel convertUpdate(OrderInfoResponse orderInfoResponse,ModifyOrderModel order) {

    // 买家备注
        order.setBuyerNote(orderInfoResponse.getData().getOrderInfo().getBuyerInfo().getBuyerRemark());
    // 确认收货时间
        order.setConfirmReceiptTime(DateUtils.stampToDate(orderInfoResponse.getData().getFulfillInfoList().get(0).getReceivingTime()));
    // 收货详细地址
        order.setDeliveryAddressDetail(orderInfoResponse.getData().getFulfillInfoList().get(0).getSendInfo().getSenderAddress());
    // 发货时间
        order.setDeliveryTime(DateUtils.stampToDate(orderInfoResponse.getData().getOrderInfo().getOrderFulfill().getDeliveryTime()));
    // 来源系统编码
        order.setFromSys("APP_DSZJJ");
    // 修改时间
        order.setModifierTime(DateUtils.dateTimeNow());
    // 卖家备注
        order.setNote(orderInfoResponse.getData().getOrderInfo().getBuyerInfo().getBuyerRemark());
        BaseOrderInfoResponse.FulfillReceiverInfo receiverInfo = orderInfoResponse.getData().getOrderInfo().getOrderFulfill().getReceiverInfo();
    // 邮编
        order.setPostalCode(receiverInfo.getZip());
    // 收货人名称
        order.setReceiverName(receiverInfo.getName());

    // 收货人手机号
        order.setReceiverPhone(receiverInfo.getPhone());
    // 收货市编码
        order.setReceivingCityCode(receiverInfo.getCityCode());
    // 收货市名称
        order.setReceivingCityName(receiverInfo.getCity());
    // 收货区县编码
        order.setReceivingDistrictCode(receiverInfo.getCountyCode());
    // 收货区县名称
        order.setReceivingDistrictName(receiverInfo.getCounty());
    // 收货省份编码
        order.setReceivingProvinceCode(receiverInfo.getProvinceCode());
    // 收货省份名称
        order.setReceivingProvinceName(receiverInfo.getProvince());
    // 收货街道编码
        order.setReceivingStreetCode(receiverInfo.getAreaCode());
    // 收货街道名称
        order.setReceivingStreetName(receiverInfo.getArea());
    // 销售订单单号
        order.setSalesOrderNo(orderInfoResponse.getData().getOrderInfo().getOrderBaseInfo().getOrderNo()+"");

    // 创建订单明细列表
        List<ModifyOrderModel.OrderItem> itemList = new ArrayList<>();

    // 创建一个订单明细实例并设置属性
        ModifyOrderModel.OrderItem item = new ModifyOrderModel.OrderItem();
        item.setConfirmReceiptTime(DateUtils.stampToDate(orderInfoResponse.getData().getFulfillInfoList().get(0).getReceivingTime()));     // 确认收货时间
        item.setLineNum("1");     // 行号
        item.setNote(orderInfoResponse.getData().getOrderInfo().getBuyerInfo().getBuyerRemark());     // 备注

    // 创建订单物流明细列表
        List<ModifyOrderModel.OrderItemLogistic> logisticList = new ArrayList<>();

    // 创建一个订单物流明细实例并设置属性
        ModifyOrderModel.OrderItemLogistic logistic = new ModifyOrderModel.OrderItemLogistic();
        BaseOrderInfoResponse.LogisticsInfo logisticsInfo = orderInfoResponse.getData().getFulfillInfoList().get(0).getConsignOrder().getLogisticsInfo();
        logistic.setCourierNo(logisticsInfo.getDeliveryNo());     // 快递单号
        logistic.setExpressCompanyName(logisticsInfo.getCompanyName());     // 快递公司名称
        logistic.setExpressCompanyNo(logisticsInfo.getCompanyCode());     // 快递公司编码
        logistic.setShipQuantity(Integer.valueOf(orderInfoResponse.getData().getOrderInfo().getItems().get(0).getProductInfos().get(0).getItemSkuQuantity()));     // 发货数量
        logistic.setShipTime(DateUtils.stampToDate(logisticsInfo.getAppointment()));    // 发货时间

    // 将物流明细添加到列表中
        logisticList.add(logistic);

    // 将物流明细列表设置到订单明细中
        item.setOrderItemLogisticList(logisticList);

    // 将订单明细添加到列表中
        itemList.add(item);

    // 将订单明细列表设置到主订单中
        order.setOrderItemList(itemList);
        return order;
    }


    /**
     * 将微盟数据转换为蒙牛需要的数据
     * @param
     * @param
     */
    private CreateOrderModel convert(OrderInfoResponse.Data orderInfoResponse, CreateOrderModel order) {
        order.setBanner(MnBannerEnum.BANNER_1.getBanner());
        /*order.setBusinessType("123");
        order.setBusinessTypeName("business");
        order.setBusinessUnitCode("unit");*/
        order.setBuyerAccount(orderInfoResponse.getOrderInfo().getOperatorInfo().getOperatorPhone());
        order.setBuyerNote(orderInfoResponse.getOrderInfo().getBuyerInfo().getBuyerRemark());
        order.setConfirmReceiptTime(DateUtils.stampToDate(orderInfoResponse.getFulfillInfoList().get(0).getReceivingTime()));
        order.setDeliveryAddressDetail(orderInfoResponse.getFulfillInfoList().get(0).getSendInfo().getSenderAddress());
        //运费
        order.setFreightAmount(getFreightAmount(orderInfoResponse.getOrderInfo().getPayInfo().getAmountInfos(),WmAmountTypeEnum.TYPE_4.getType()));
        order.setFromSys("APP_DSZJJ");
        order.setModifierTime(DateUtils.dateTimeNow());
        order.setNote(orderInfoResponse.getOrderInfo().getBuyerInfo().getBuyerRemark());

        List<CreateOrderModel.OrderItem> orderItemList = new ArrayList<>();
        //循环
        CreateOrderModel.OrderItem orderItem = new CreateOrderModel.OrderItem();
        orderItem.setBuyItemNo("123");
        orderItem.setGiftFlag("Y");
        orderItem.setInnerProductCode(orderInfoResponse.getOrderInfo().getItems().get(0).getProductInfos().get(0).getCombSkuId()+"");
        orderItem.setInnerProductName(orderInfoResponse.getOrderInfo().getItems().get(0).getProductInfos().get(0).getTitle());
        orderItem.setNote("微盟创建订单");
        orderItem.setPlannedDeliveryTime(DateUtils.stampToDate(orderInfoResponse.getOrderInfo().getOrderFulfill().getDeliveryTime()));
        orderItem.setProductBarCode(orderInfoResponse.getOrderInfo().getItems().get(0).getSkuBarCode());
        orderItem.setProductQuantity(Integer.valueOf(orderInfoResponse.getOrderInfo().getItems().get(0).getProductInfos().get(0).getItemSkuQuantity()));
        orderItem.setItemPromotionAmount(orderInfoResponse.getOrderInfo().getItems().get(0).getDiscountInfos().get(0).getCostAmount());
        orderItem.setSalesUnitCode(orderInfoResponse.getOrderInfo().getMerchantInfo().getMerchantExtInfo().getOutShopCode());
        orderItem.setSalesUnitName(orderInfoResponse.getOrderInfo().getMerchantInfo().getMerchantExtInfo().getOutShopName());
        orderItem.setSourceOrderItemNo(orderInfoResponse.getOrderInfo().getOrderBaseInfo().getOrderNo()+"");
        //orderItem.setStockConversionNum(10);
        orderItem.setStockUnitCode(orderInfoResponse.getOrderInfo().getItems().get(0).getUnitType()+"");
        orderItem.setStockUnitName(orderInfoResponse.getOrderInfo().getItems().get(0).getUnitName());
        orderItem.setTotalAmount(orderInfoResponse.getOrderInfo().getPayInfo().getTotalAmount());
        //orderItem.setUnitConversionRelationship(5);
        orderItem.setUnitPrice(orderInfoResponse.getOrderInfo().getItems().get(0).getSalePrice());

        //活动赞不同步
        /*List<CreateOrderModel.OrderItemActivity> orderItemActivityList = new ArrayList<>();
        CreateOrderModel.OrderItemActivity orderItemActivity = new CreateOrderModel.OrderItemActivity();
        orderItemActivity.setActivityId("activity id");
        orderItemActivity.setActivityType("activity type");

        orderItemActivityList.add(orderItemActivity);
        orderItem.setOrderItemActivityList(orderItemActivityList);*/

        List<CreateOrderModel.OrderItemLogistic> orderItemLogisticList = new ArrayList<>();
        CreateOrderModel.OrderItemLogistic orderItemLogistic = new CreateOrderModel.OrderItemLogistic();
        BaseOrderInfoResponse.LogisticsInfo logisticsInfo = orderInfoResponse.getFulfillInfoList().get(0).getConsignOrder().getLogisticsInfo();
        orderItemLogistic.setCourierNo(logisticsInfo.getDeliveryNo());
        orderItemLogistic.setExpressCompanyName(logisticsInfo.getCompanyName());
        orderItemLogistic.setExpressCompanyNo(logisticsInfo.getCompanyCode());
        orderItemLogistic.setShipQuantity(Integer.valueOf(orderInfoResponse.getOrderInfo().getItems().get(0).getProductInfos().get(0).getItemSkuQuantity()));
        orderItemLogistic.setShipTime(DateUtils.stampToDate(logisticsInfo.getAppointment()));

        orderItemLogisticList.add(orderItemLogistic);
        orderItem.setOrderItemLogisticList(orderItemLogisticList);

        orderItemList.add(orderItem);
        order.setOrderItemList(orderItemList);

        order.setPaidAmount(orderInfoResponse.getOrderInfo().getPayInfo().getPayAmount());
        order.setPayableAmount(orderInfoResponse.getOrderInfo().getPayInfo().getShouldPayAmount());
        BaseOrderInfoResponse.FulfillReceiverInfo receiverInfo = orderInfoResponse.getOrderInfo().getOrderFulfill().getReceiverInfo();
        order.setPostalCode(receiverInfo.getZip());
        order.setPromotionAmount(orderInfoResponse.getOrderInfo().getPayInfo().getPayItems().get(0).getPayCouponInfos().get(0).getAmount()+"");
        //收货人

        order.setReceiverName(receiverInfo.getName());
        order.setReceiverPhone(receiverInfo.getPhone());
        order.setReceivingCityCode(receiverInfo.getCityCode());
        order.setReceivingCityName(receiverInfo.getCity());
           // order.setReceivingCountryCode(receiverInfo.getCountyCode());
        //order.setReceivingCountryName(receiverInfo.getCounty());
        order.setReceivingDistrictCode(receiverInfo.getCountyCode());
        order.setReceivingDistrictName(receiverInfo.getCounty());
        order.setReceivingProvinceCode(receiverInfo.getProvinceCode());
        order.setReceivingProvinceName(receiverInfo.getProvince());
        order.setReceivingStreetCode(receiverInfo.getAreaCode());
        order.setReceivingStreetName(receiverInfo.getArea());
        order.setSalesOrderType("1");
        order.setShipTime(DateUtils.stampToDate(orderInfoResponse.getOrderInfo().getOrderFulfill().getDeliveryTime()));
        order.setSourceOrderNo(orderInfoResponse.getOrderInfo().getOrderBaseInfo().getOrderNo()+"");
        order.setStoreCode("1000061124");
        order.setStoreName("测试店铺");
        order.setSourceCreateTime(DateUtils.stampToDate(orderInfoResponse.getOrderInfo().getOrderBaseInfo().getCreateTime()));
        return order;
    }

    /**
     * 获取金额
     * @return
     */
    public String getFreightAmount(List<BaseOrderInfoResponse.AmountInfo> list , Integer type){
        String theAmount ="0";
        Optional<String> amount = list.stream()
                .filter(item -> item.getType().equals(type))
                .map(item -> item.getAmount())
                .findFirst();
            // 使用该值时需要判断是否存在
        if (amount.isPresent()) {
             theAmount = amount.get();
                // 使用 theAmount
        }
        return theAmount;
    }


}
